<template>
  <div class="teacher-audit-page">
    <a-page-header title="教员审核" sub-title="审核教员申请资料"/>

    <a-card class="card-shadow">
      <!-- 标签页 -->
      <a-tabs v-model:activeKey="activeTab" @change="handleTabChange">
        <a-tab-pane key="PENDING" tab="待审核">
          <a-spin :spinning="loading">
            <a-empty v-if="pendingList.length === 0" description="暂无待审核教员">
              <a-button type="primary" @click="loadData">刷新</a-button>
            </a-empty>

            <a-list
                v-else
                :data-source="pendingList"
                item-layout="vertical"
            >
              <template #renderItem="{ item }">
                <a-list-item>
                  <template #actions>
                    <a-button type="primary" @click="handleApprove(item)">
                      <template #icon>
                        <check-outlined/>
                      </template>
                      通过
                    </a-button>
                    <a-button danger @click="handleReject(item)">
                      <template #icon>
                        <close-outlined/>
                      </template>
                      拒绝
                    </a-button>
                  </template>

                  <a-list-item-meta>
                    <template #avatar>
                      <a-avatar
                          :src="item.avatarUrl || 'https://api.dicebear.com/7.x/avataaars/svg?seed=' + item.userId"
                          :size="64"/>
                    </template>
                    <template #title>
                      <a-space>
                        <span style="font-size: 18px; font-weight: bold;">{{ item.realName }}</span>
                        <a-tag color="blue">待审核</a-tag>
                      </a-space>
                    </template>
                    <template #description>
                      <a-descriptions :column="3" size="small" style="margin-top: 12px;">
                        <a-descriptions-item label="手机号">{{ item.mobile }}</a-descriptions-item>
                        <a-descriptions-item label="学校">{{ item.school || '-' }}</a-descriptions-item>
                        <a-descriptions-item label="学历">{{ item.education || '-' }}</a-descriptions-item>
                        <a-descriptions-item label="科目" :span="3">{{ item.subjects || '-' }}</a-descriptions-item>
                        <a-descriptions-item label="提交时间" :span="3">{{
                            formatTime(item.submittedAt)
                          }}
                        </a-descriptions-item>
                      </a-descriptions>
                    </template>
                  </a-list-item-meta>

                  <div class="audit-content">
                    <h4 style="margin-bottom: 12px;">证件照片</h4>
                    <a-space :size="16">
                      <div class="cert-image">
                        <a-image
                            :src="item.idFrontPath || 'https://via.placeholder.com/200x150?text=身份证正面'"
                            width="200"
                            :preview="true"
                        />
                        <div class="image-label">身份证正面</div>
                      </div>
                      <div class="cert-image">
                        <a-image
                            :src="item.idBackPath || 'https://via.placeholder.com/200x150?text=身份证反面'"
                            width="200"
                            :preview="true"
                        />
                        <div class="image-label">身份证反面</div>
                      </div>
                      <div class="cert-image">
                        <a-image
                            :src="item.selfiePath || 'https://via.placeholder.com/200x150?text=手持身份证照片'"
                            width="200"
                            :preview="true"
                        />
                        <div class="image-label">手持身份证照片</div>
                      </div>
                    </a-space>
                  </div>
                </a-list-item>
              </template>
            </a-list>
          </a-spin>
        </a-tab-pane>

        <a-tab-pane key="APPROVED" tab="已通过">
          <a-spin :spinning="loading">
            <a-empty v-if="approvedList.length === 0" description="暂无已通过记录"/>

            <a-list
                v-else
                :data-source="approvedList"
                item-layout="vertical"
            >
              <template #renderItem="{ item }">
                <a-list-item>
                  <a-list-item-meta>
                    <template #avatar>
                      <a-avatar
                          :src="item.avatarUrl || 'https://api.dicebear.com/7.x/avataaars/svg?seed=' + item.userId"
                          :size="64"/>
                    </template>
                    <template #title>
                      <a-space>
                        <span style="font-size: 18px; font-weight: bold;">{{ item.realName }}</span>
                        <a-tag color="green">已通过</a-tag>
                      </a-space>
                    </template>
                    <template #description>
                      <a-descriptions :column="3" size="small">
                        <a-descriptions-item label="手机号">{{ item.mobile }}</a-descriptions-item>
                        <a-descriptions-item label="学校">{{ item.school || '-' }}</a-descriptions-item>
                        <a-descriptions-item label="学历">{{ item.education || '-' }}</a-descriptions-item>
                        <a-descriptions-item label="审核时间" :span="3">{{
                            formatTime(item.auditedAt)
                          }}
                        </a-descriptions-item>
                      </a-descriptions>
                    </template>
                  </a-list-item-meta>
                </a-list-item>
              </template>
            </a-list>
          </a-spin>
        </a-tab-pane>

        <a-tab-pane key="REJECTED" tab="已拒绝">
          <a-spin :spinning="loading">
            <a-empty v-if="rejectedList.length === 0" description="暂无已拒绝记录"/>

            <a-list
                v-else
                :data-source="rejectedList"
                item-layout="vertical"
            >
              <template #renderItem="{ item }">
                <a-list-item>
                  <a-list-item-meta>
                    <template #avatar>
                      <a-avatar
                          :src="item.avatarUrl || 'https://api.dicebear.com/7.x/avataaars/svg?seed=' + item.userId"
                          :size="64"/>
                    </template>
                    <template #title>
                      <a-space>
                        <span style="font-size: 18px; font-weight: bold;">{{ item.realName }}</span>
                        <a-tag color="red">已拒绝</a-tag>
                      </a-space>
                    </template>
                    <template #description>
                      <a-descriptions :column="3" size="small">
                        <a-descriptions-item label="手机号">{{ item.mobile }}</a-descriptions-item>
                        <a-descriptions-item label="学校">{{ item.school || '-' }}</a-descriptions-item>
                        <a-descriptions-item label="学历">{{ item.education || '-' }}</a-descriptions-item>
                        <a-descriptions-item label="拒绝理由" :span="3">{{
                            item.auditNote || '-'
                          }}
                        </a-descriptions-item>
                        <a-descriptions-item label="审核时间" :span="3">{{
                            formatTime(item.auditedAt)
                          }}
                        </a-descriptions-item>
                      </a-descriptions>
                    </template>
                  </a-list-item-meta>
                </a-list-item>
              </template>
            </a-list>
          </a-spin>
        </a-tab-pane>
      </a-tabs>
    </a-card>

    <!-- 拒绝理由弹窗 -->
    <a-modal
        v-model:open="rejectModalVisible"
        title="拒绝审核"
        @ok="handleRejectConfirm"
    >
      <a-alert
          message="请填写拒绝理由"
          description="拒绝理由将会通知给教员，请认真填写。"
          type="warning"
          show-icon
          style="margin-bottom: 16px;"
      />
      <a-textarea
          v-model:value="rejectReason"
          placeholder="请输入拒绝理由"
          :rows="4"
          :maxlength="200"
          show-count
      />
    </a-modal>
  </div>
</template>

<script setup>
import {ref, onMounted} from 'vue'
import {message, Modal} from 'ant-design-vue'
import {CheckOutlined, CloseOutlined} from '@ant-design/icons-vue'
import {getPendingAuditList, getAuditListByStatus, auditTeacherIdentity} from '@/api/teacher'
import dayjs from 'dayjs'

const activeTab = ref('PENDING')
const loading = ref(false)
const rejectModalVisible = ref(false)
const rejectReason = ref('')
const currentItem = ref(null)

const pendingList = ref([])
const approvedList = ref([])
const rejectedList = ref([])

const loadData = async () => {
  loading.value = true

  try {
    // 根据当前标签页加载不同的数据
    if (activeTab.value === 'PENDING') {
      const res = await getPendingAuditList()
      if (res.data) {
        pendingList.value = res.data
        console.log('待审核列表:', pendingList.value)
      }
    } else if (activeTab.value === 'APPROVED') {
      // 获取已通过的列表
      const res = await getAuditListByStatus('APPROVED')
      if (res.data) {
        approvedList.value = res.data
      }
    } else if (activeTab.value === 'REJECTED') {
      // 获取已拒绝的列表
      const res = await getAuditListByStatus('REJECTED')
      if (res.data) {
        rejectedList.value = res.data
      }
    }
  } catch (error) {
    console.error('加载审核列表失败:', error)
    message.error(error.message || '加载审核列表失败')
  } finally {
    loading.value = false
  }
}

const handleTabChange = (key) => {
  activeTab.value = key
  loadData()
}


const handleApprove = (item) => {
  Modal.confirm({
    title: '确认通过',
    content: `确定通过 ${item.realName} 的教员认证申请吗？`,
    okText: '确定',
    cancelText: '取消',
    onOk: async () => {
      try {
        await auditTeacherIdentity({
          userId: item.userId,
          status: 'APPROVED',
          auditNote: '审核通过'
        })

        message.success('审核通过')
        loadData()
      } catch (error) {
        message.error(error.message || '审核失败')
      }
    }
  })
}

const handleReject = (item) => {
  currentItem.value = item
  rejectReason.value = ''
  rejectModalVisible.value = true
}

const handleRejectConfirm = async () => {
  if (!rejectReason.value || rejectReason.value.trim() === '') {
    message.error('请输入拒绝理由')
    return
  }

  try {
    await auditTeacherIdentity({
      userId: currentItem.value.userId,
      status: 'REJECTED',
      auditNote: rejectReason.value
    })

    message.success('已拒绝该申请')
    rejectModalVisible.value = false
    rejectReason.value = ''
    loadData()
  } catch (error) {
    message.error(error.message || '操作失败')
  }
}

const formatTime = (time) => {
  if (!time) return '-'
  return dayjs(time).format('YYYY-MM-DD HH:mm:ss')
}

onMounted(() => {
  loadData()
})
</script>

<style lang="scss" scoped>
.teacher-audit-page {
  .audit-content {
    margin-top: 24px;
    padding: 20px;
    background: #fafafa;
    border-radius: 8px;

    h4 {
      margin-bottom: 12px;
      color: #333;
    }

    .cert-image {
      text-align: center;

      .image-label {
        margin-top: 8px;
        font-size: 12px;
        color: #666;
      }
    }
  }
}
</style>
